package com.xyz.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.xyz.config.SystemData;
import com.xyz.dao.mapper.MessageGroupMapper;
import com.xyz.dao.mapper.UpkeepDaoMapper;
import com.xyz.dao.pojo.MessageGroupVo;
import com.xyz.dto.enums.EnumPatrolState;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.MessageService;
import com.xyz.service.PatrolService;
import com.xyz.service.impl.MessageServiceImpl;
import com.xyz.util.RedisUtil;
import com.xyz.util.dto.LoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

// 定时任务
@EnableScheduling
@Component
@Transactional(rollbackFor = Exception.class)
public class Task {

    private static final Logger logger = LoggerFactory.getLogger(Task.class);

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParameterMapper systemParameterMapper;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private RepairMaintenanceMapper repairMaintenanceMapper;

    @Autowired
    private RepairWorkOrderFlowMapper repairWorkOrderFlowMapper;

    @Autowired
    private UpkeepMaintenanceMapper upkeepMaintenanceMapper;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private PlanInfoMapper planInfoMapper;

    @Autowired
    private PatrolService patrolService;

    @Autowired
    private PatrolWorkOrderMapper patrolWorkOrderMapper;

    @Autowired
    private TemplatePlanMapper templatePlanMapper;

    @Autowired
    private TemplatePlanTaskMapper templatePlanTaskMapper;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private MessageInfoMapper messageInfoMapper;

    @Autowired
    private MessageGroupMapper messageGroupMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private UpkeepTaskMapper upkeepTaskMapper;

    @Autowired
    private UpkeepDaoMapper UpkeepDao;

    @Autowired
    private PatrolWorkOrderFlowMapper patrolWorkOrderFlowMapper;

    @Autowired
    private EquipmentTreeMapper equipmentTreeMapper;

    @Autowired
    private PatrolPlanMapper patrolPlanMapper;

    @Autowired
    private PatrolTemplateTaskMapper patrolTemplateTaskMapper;

    @Autowired
    private PatrolTreeMapper patrolTreeMapper;

    @Autowired
    private PatrolTreeTaskMapper patrolTreeTaskMapper;

    @Autowired
    private UpkeepTemplateTaskMapper upkeepTemplateTaskMapper;

    @Autowired
    private UpkeepDbTaskMapper upkeepDbTaskMapper;

    @Autowired
    private PatrolTemplateSubsystemMapper patrolTemplateSubsystemMapper;

    @Autowired
    private RedisUtil redis;

    // 项目启动时执行一次
    @PostConstruct
    public void init() throws Exception {
        logger.info("程序正在启动>>>" + DateUtil.now());
        // 加载员工数据
        commonService.updateEmployeeMap();
    }

    // 推送消息
    @Scheduled(fixedDelay = 15000)
    public void sendMessageTask() {
        Set<String> tokenSet = MessageServiceImpl.sseEmitterMap.keySet();
        if (tokenSet.size() == 0) {
            return;
        }
        Map<String, String> tokenMap = new HashMap<>();
        List<Long> userIdLise = new ArrayList<>();
        try {
            for (String token : tokenSet) {
                String tokenValue = redis.get(token);
                LoginInfo li = JSONUtil.toBean(tokenValue, LoginInfo.class);
                tokenMap.put(token, li.getLoginUserId() + "");
                userIdLise.add(li.getLoginUserId());
            }
        } catch (Exception e) {
            logger.error("redis不存在sse的token");
        }
        if (userIdLise.size() == 0) {
            return;
        }

        MessageInfoExample miExample = new MessageInfoExample();
        MessageInfoExample.Criteria criteria = miExample.createCriteria();
        criteria.andUserIdIn(userIdLise);
        criteria.andStateEqualTo(1);
        criteria.andCreateTimeGreaterThanOrEqualTo(DateUtil.offsetSecond(new Date(), -15));
        miExample.setOrderByClause("create_time asc");
        List<MessageInfo> miList = messageInfoMapper.selectByExample(miExample);
        Map<String, Map<String, Object>> miPopupMap = new HashMap<>();
        for (MessageInfo mi : miList) {
            Map<String, Object> miPopup = new HashMap<>();
            miPopup.put("id", mi.getId());
            miPopup.put("title", mi.getTitle());
            miPopup.put("content", mi.getContent());
            miPopup.put("state", mi.getState());
            miPopup.put("businessType", mi.getBusinessType());
            miPopup.put("businessId", mi.getBusinessId());
            miPopup.put("businessCode", mi.getBusinessId());
            miPopup.put("time", mi.getCreateTime());
            miPopupMap.put(mi.getUserId() + "", miPopup);
        }

        List<MessageGroupVo> mgList = messageGroupMapper.selectMessageGroup(userIdLise);
        Map<String, Integer> mgMap = new HashMap<>();
        for (MessageGroupVo mg : mgList) {
            mgMap.put(mg.getUserId() + "," + mg.getMessageType() + "," + mg.getState(), mg.getCount());
        }

        Map<String, Map<String, Object>> map = new HashMap<>();
        for (String token : tokenMap.keySet()) {
            String userIdStr = tokenMap.get(token);

            Map<String, Integer> isReadMap = new HashMap<>();
            isReadMap.put("notice", mgMap.getOrDefault(userIdStr + ",1,2", 0));  // 已读，消息
            isReadMap.put("toDo", mgMap.getOrDefault(userIdStr + ",2,2", 0));  // 已读，待办

            Map<String, Integer> unReadMap = new HashMap<>();
            unReadMap.put("notice", mgMap.getOrDefault(userIdStr + ",1,1", 0));  // 未读，消息
            unReadMap.put("toDo", mgMap.getOrDefault(userIdStr + ",2,1", 0));  // 未读，待办


            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("isRead", isReadMap);
            dataMap.put("unRead", unReadMap);
            dataMap.put("newMsgs", miPopupMap.getOrDefault(userIdStr, null));
            map.put(token, dataMap);
        }
        messageService.sendMessage(map);
    }

    // 每日单据数据归0
    @Scheduled(cron = "0 0 0 * * ?")
    public void numberTask() {
        List<String> keyList = CollUtil.newArrayList(
                "PART_IN_NUMBER",
                "PART_OUT_NUMBER",
                "PART_APPLY_NUMBER",
                "PART_INVENTORY_NUMBER",
                SystemData.UPKEEP_WORK_NUMBER,
                SystemData.REPAIR_WORK_NUMBER,
                SystemData.PATROL_WORK_NUMBER
        );
        SystemParameter sp = new SystemParameter();
        sp.setParameterValue("0");
        SystemParameterExample spExample = new SystemParameterExample();
        spExample.createCriteria().andParameterKeyIn(keyList);
        systemParameterMapper.updateByExampleSelective(sp, spExample);
        logger.info("每日单据数据归0>>>" + DateUtil.now());
    }


    /*
     * 执行方式为运行时长的计划维保计划
     * */
    @Scheduled(cron = "0 0 0 * * ?")
    public void insertPlanUpkeepTask() {
        //查询运行时长的计划模板
        UpkeepTemplateTaskExample templateExample = new UpkeepTemplateTaskExample();
        UpkeepTemplateTaskExample.Criteria templateCriteria = templateExample.createCriteria();
        templateCriteria.andModeTypeEqualTo(2);
        templateCriteria.andStateEqualTo(2);
        List<UpkeepTemplateTask> upkeepTemplateTaskList = upkeepTemplateTaskMapper.selectByExample(templateExample);
        Date date = new Date();
        for (UpkeepTemplateTask upkeepTemplateTask : upkeepTemplateTaskList) {
            //查询每个模板对应的最新的计划数据
            PlanInfoExample planExample = new PlanInfoExample();
            PlanInfoExample.Criteria planCriteria = planExample.createCriteria();
            planCriteria.andPlanTypeEqualTo(1);
            planCriteria.andTemplateIdEqualTo(upkeepTemplateTask.getId());
            planExample.setOrderByClause("change_time desc limit 1");
            List<PlanInfo> planInfoList = planInfoMapper.selectByExample(planExample);
            if(CollUtil.isNotEmpty(planInfoList)){
                PlanInfo planInfo = planInfoList.get(0);
                //相隔天数
                long between = DateUtil.between(planInfo.getChangeTime(), date, DateUnit.DAY);
                Integer runningDayTime = upkeepTemplateTask.getRunningDayTime();
                Integer runningTime = upkeepTemplateTask.getRunningTime();
                if (runningDayTime != null && runningTime != null) {
                    if ((runningDayTime * between) >= runningTime) {
                        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(upkeepTemplateTask.getEmId());
                        UpkeepDbTask upkeepDbTask = upkeepDbTaskMapper.selectByPrimaryKey(upkeepTemplateTask.getDbTaskId());
                        PlanInfo insertPlanInfo = new PlanInfo();
                        insertPlanInfo.setEmId(upkeepTemplateTask.getEmId());
                        insertPlanInfo.setTreeId(upkeepTemplateTask.getTreeId());
                        insertPlanInfo.setPlanType(1);
                        insertPlanInfo.setTemplateId(upkeepTemplateTask.getId());
                        insertPlanInfo.setTemplateName(equipmentInfo.getEmName() + "-" + upkeepDbTask.getTaskName());
                        insertPlanInfo.setIsGenerate(1);
                        insertPlanInfo.setIsDelete(1);
                        planInfo.setChangeTime(date);
                        planInfo.setYear(DateUtil.year(date));
                        planInfo.setMonth(DateUtil.month(date)+1);
                        planInfo.setDay(DateUtil.dayOfMonth(date));
                        planInfo.setCreateTime(date);
                        planInfoMapper.insertSelective(planInfo);
                    }

                }
            }
        }
    }

    /*
    * 每天生产
    * 维保计划生成工单
    * */
    @Scheduled(cron = "0 0 1 * * ?")
    public void planUpkeepRoTask() {
        UpkeepTemplateTaskExample templateExample = new UpkeepTemplateTaskExample();
        UpkeepTemplateTaskExample.Criteria templateCriteria = templateExample.createCriteria();
        templateCriteria.andModeTypeEqualTo(2);
        templateCriteria.andStateEqualTo(2);
        List<UpkeepTemplateTask> upkeepTemplateTaskList = upkeepTemplateTaskMapper.selectByExample(templateExample);
        Date date = new Date();
        upkeepTemplateTaskList.forEach(item -> {
            Date planEndTime = item.getPlanEndTime();
            if (date.before(planEndTime)) {
                logger.info("upkeepTemplateTaskList-------->id为：{}，状态变更为已过期", item.getId());
                UpkeepTemplateTask upkeepTemplateTask = new UpkeepTemplateTask();
                upkeepTemplateTask.setId(item.getId());
                upkeepTemplateTask.setState(5);
                upkeepTemplateTaskMapper.updateByPrimaryKey(upkeepTemplateTask);
            }
        });

        //获取定时时间
        List<SystemDictData> planDay = commonService.getSysDateListByCode("TYPE_PLAN_DAY");
        Map<Long, EquipmentTree> equipmentTreeMap = commonService.getEquipmentTreeMap();
        int day = planDay.size() > 0 ? planDay.get(0).getDictValue() : 5;
        //查询维保计划

        Date startTime = DateUtil.beginOfDay(date);
        PlanInfoExample piExample = new PlanInfoExample();
        PlanInfoExample.Criteria piCriteria = piExample.createCriteria();
        //PlanType =1 维保计划
        piCriteria.andPlanTypeEqualTo(1);
        piCriteria.andIsGenerateEqualTo(1);
        piCriteria.andIsDeleteEqualTo(1);
        piCriteria.andChangeTimeBetween(startTime, DateUtil.offsetDay(startTime, day));
        List<PlanInfo> piList = planInfoMapper.selectByExample(piExample);
        for (PlanInfo info : piList) {
            insertUpkeep(info, equipmentTreeMap);
            PlanInfo updareInfo = new PlanInfo();
            updareInfo.setId(info.getId());
            updareInfo.setIsGenerate(2);
            planInfoMapper.updateByPrimaryKeySelective(updareInfo);
        }
    }

    /*
    * 10秒一次
    * 巡检计划生成单据
    * */
    @Scheduled(fixedDelay = 10000)
    public void planTask() throws Exception {
        Date currentDate = new Date();
        PlanInfoExample piExample = new PlanInfoExample();
        PlanInfoExample.Criteria piCriteria = piExample.createCriteria();
        //PlanType =2 巡检计划
        piCriteria.andPlanTypeEqualTo(2);
        piCriteria.andIsGenerateEqualTo(1);
        piCriteria.andIsDeleteEqualTo(1);
        piCriteria.andMinuteTimeLessThanOrEqualTo(currentDate);
        List<PlanInfo> piList = planInfoMapper.selectByExample(piExample);
        Map<Long, EquipmentTree> equipmentTreeMap = commonService.getEquipmentTreeMap();
        for (PlanInfo info : piList) {
            insertPatrol(info,equipmentTreeMap);
            //计算过期标签
            overduePatrol(info);
            PlanInfo updareInfo = new PlanInfo();
            updareInfo.setId(info.getId());
            updareInfo.setIsGenerate(2);
            planInfoMapper.updateByPrimaryKeySelective(updareInfo);
        }
        logger.info("每日计划转工单>>>" + DateUtil.now());
    }

    /*
     * 判断巡检过期
     * */
    @Scheduled(fixedDelay = 1000)
    public void updateIsTimeout() {
        Date date = new Date();
        List<SystemDictData> planDay = commonService.getSysDateListByCode("PATROL_RO_TIMEOUT_MINUTE");
        if(CollUtil.isNotEmpty(planDay)){
            //配置的过期时间(分钟)
            long dictValue = planDay.get(0).getDictValue() * 60;
            //查询没过期的巡检单
            PatrolWorkOrderExample patrolExample = new PatrolWorkOrderExample();
            PatrolWorkOrderExample.Criteria patrolCriteria = patrolExample.createCriteria();
            patrolCriteria.andStateEqualTo(EnumPatrolState.ALLOCATED.getState());
            patrolCriteria.andIsAcdTimeoutEqualTo(0);
            List<PatrolWorkOrder> patrolWorkOrders = patrolWorkOrderMapper.selectByExample(patrolExample);
            for (PatrolWorkOrder patrolWorkOrder:patrolWorkOrders){
                if(patrolWorkOrder.getAssStartTime() != null){
                    long between = DateUtil.between(patrolWorkOrder.getAssStartTime(), date, DateUnit.SECOND);
                    if(between > dictValue){
                        PatrolWorkOrder updateOrder = new PatrolWorkOrder();
                        updateOrder.setId(patrolWorkOrder.getId());
                        updateOrder.setIsAcdTimeout(1);
                        patrolWorkOrderMapper.updateByPrimaryKeySelective(updateOrder);
                    }
                }
            }
        }

    }

    // // 半秒执行一次
    // @Scheduled(fixedDelay = 500)
    // public void sourceTask() {
    //     //查询已分配维修工单，到规定时间自动变成维修中
    //     RepairMaintenanceExample repManinExample = new RepairMaintenanceExample();
    //     RepairMaintenanceExample.Criteria repManinCriteria = repManinExample.createCriteria();
    //     repManinCriteria.andMtcStateEqualTo(EnumRepState.ALLOCATED.getRepState());
    //     repManinCriteria.andCreateTimeLessThan(DateUtil.offsetSecond(new Date(), SystemData.repAutoTime));
    //     List<RepairMaintenance> repairMaintenances = repairMaintenanceMapper.selectByExample(repManinExample);
    //     if (CollUtil.isNotEmpty(repairMaintenances)) {
    //         for (RepairMaintenance repairMaintenance : repairMaintenances) {
    //             //修改维修单状态
    //             RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
    //             updateRepairMaintenance.setId(repairMaintenance.getId());
    //             updateRepairMaintenance.setMtcState(EnumRepState.UNDE_REPAIR.getRepState());
    //             updateRepairMaintenance.setProcessType(1);
    //             updateRepairMaintenance.setMtcStartTime(new Date());
    //             repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
    //             RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
    //             updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
    //             updateRepairWorkOrder.setRepState(EnumRepState.UNDE_REPAIR.getRepState());
    //             repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
    //             insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.UNDE_REPAIR.getRepState(), "自动维修中");
    //
    //         }
    //     }
    // }
    //
    // // 半秒执行一次
    // @Scheduled(fixedDelay = 500)
    // public void sourceUpkeepTask() {
    //     //查询已分配维修工单，到规定时间自动变成维修中
    //     UpkeepMaintenanceExample upkeepManinExample = new UpkeepMaintenanceExample();
    //     UpkeepMaintenanceExample.Criteria upkeepManinCriteria = upkeepManinExample.createCriteria();
    //     upkeepManinCriteria.andMtcStateEqualTo(EnumRepState.ALLOCATED.getRepState());
    //     upkeepManinCriteria.andCreateTimeLessThan(DateUtil.offsetSecond(new Date(), SystemData.upkeepAutoTime));
    //     List<UpkeepMaintenance> upkeepMaintenances = upkeepMaintenanceMapper.selectByExample(upkeepManinExample);
    //     if (CollUtil.isNotEmpty(upkeepMaintenances)) {
    //         for (UpkeepMaintenance upkeepMaintenance : upkeepMaintenances) {
    //             //修改维修单状态
    //             UpkeepMaintenance updateUpkeepMaintenance = new UpkeepMaintenance();
    //             updateUpkeepMaintenance.setId(upkeepMaintenance.getId());
    //             updateUpkeepMaintenance.setMtcState(EnumRepState.UNDE_REPAIR.getRepState());
    //             updateUpkeepMaintenance.setProcessType(1);
    //             updateUpkeepMaintenance.setMtcStartTime(new Date());
    //             upkeepMaintenanceMapper.updateByPrimaryKeySelective(updateUpkeepMaintenance);
    //             UpkeepWorkOrder updateUpkeepWorkOrder = new UpkeepWorkOrder();
    //             updateUpkeepWorkOrder.setUpkeepId(upkeepMaintenance.getUpkeepId());
    //             updateUpkeepWorkOrder.setUpkeepState(EnumRepState.UNDE_REPAIR.getRepState());
    //             upkeepWorkOrderMapper.updateByPrimaryKeySelective(updateUpkeepWorkOrder);
    //             insertFlow(upkeepMaintenance.getUpkeepId(), upkeepMaintenance.getEmployeeId(), 3, upkeepMaintenance.getId(), EnumRepState.UNDE_REPAIR.getRepState(), "自动维保中");
    //         }
    //     }
    // }

    private void overduePatrol(PlanInfo planInfo){
        PlanInfoExample piExample = new PlanInfoExample();
        PlanInfoExample.Criteria piCriteria = piExample.createCriteria();
        //PlanType =2 巡检计划
        piCriteria.andPlanTypeEqualTo(2);
        piCriteria.andIsDeleteEqualTo(1);
        piCriteria.andTemplateIdEqualTo(planInfo.getTemplateId());
        piCriteria.andMinuteTimeLessThan(planInfo.getMinuteTime());
        piExample.setOrderByClause("minute_time desc limit 1");
        List<PlanInfo> piList = planInfoMapper.selectByExample(piExample);
        if(CollUtil.isNotEmpty(piList)){
            PlanInfo getplanInfo = piList.get(0);
            if(getplanInfo.getIsGenerate() == 2){
                PatrolWorkOrderExample example = new PatrolWorkOrderExample();
                example.createCriteria().andPlanIdEqualTo(getplanInfo.getId());
                List<PatrolWorkOrder> patrolWorkOrders = patrolWorkOrderMapper.selectByExample(example);
                if(CollUtil.isNotEmpty(patrolWorkOrders)){
                    PatrolWorkOrder patrolWorkOrder = patrolWorkOrders.get(0);
                    if(patrolWorkOrder.getState().equals(EnumPatrolState.PENDING_RECEIVE.getState())){
                        patrolWorkOrder.setIsOverdue(1);
                        patrolWorkOrderMapper.updateByPrimaryKeySelective(patrolWorkOrder);
                    }

                }
            }
        }
    }

    /*
    * 新增巡检单
    * */
    private void insertPatrol(PlanInfo planInfo,Map<Long, EquipmentTree> equipmentTreeMap){
        PatrolPlan patrolPlan = patrolPlanMapper.selectByPrimaryKey(planInfo.getTemplateId());
        PatrolWorkOrder newPwo = new PatrolWorkOrder();
        newPwo.setCode(commonService.getPatrolCode());
        newPwo.setTreeId(planInfo.getTreeId());
        newPwo.setState(EnumPatrolState.PENDING_RECEIVE.getState());
        newPwo.setStartTime(planInfo.getMinuteTime());
        newPwo.setIsException(0);
        newPwo.setCreateEmployeeId(0L);
        newPwo.setPatrolEmployeeId(0L);
        newPwo.setCreateTime(new Date());
        newPwo.setBusinessType(patrolPlan.getBusinessType());
        newPwo.setPlanId(planInfo.getId());
        newPwo.setTeamGroup(patrolPlan.getTeamGroup());
        patrolWorkOrderMapper.insertSelective(newPwo);

        insertPatroFlow(newPwo.getId(), 1, 0, 0L, "", new Date());
        insertTask(newPwo.getId(), planInfo.getTreeId());

        /*EquipmentTree tree3 = equipmentTreeMap.get(planInfo.getTreeId());
        EquipmentTree tree2 = new EquipmentTree();
        EquipmentTree tree1 = new EquipmentTree();
        if (tree3 != null) {
            tree2 = equipmentTreeMap.get(tree3.getBaseId());
            if (tree2 != null) {
                tree1 = equipmentTreeMap.get(tree2.getBaseId());
            }
        } else {
            tree3 = new EquipmentTree();
        }
        try {
            for (long userId : commonService.selectManagerUserIdList(4)) {
                commonService.insertMessageBacklog(
                        userId,
                        "新增巡检单待审核，请处理",
                        "【" + tree1.getName() + "-" + tree2.getName() + "-" + tree3.getName() + "】新增巡检任务，请审核巡检单信息。",
                        4, 1, newPwo.getId(), newPwo.getCode()
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    /*
     新增维保工单
    * */
    private void insertUpkeep(PlanInfo planInfo, Map<Long, EquipmentTree> equipmentTreeMap) {
        UpkeepWorkOrder upkeepWorkOrder = new UpkeepWorkOrder();
        upkeepWorkOrder.setPlanId(planInfo.getId());
        upkeepWorkOrder.setEmId(planInfo.getEmId());
        upkeepWorkOrder.setTreeId(planInfo.getTreeId());
        EquipmentTree equipmentTree = equipmentTreeMap.get(planInfo.getTreeId());
        if (equipmentTree == null) {
            upkeepWorkOrder.setTreeName("");
        } else {
            upkeepWorkOrder.setTreeName(equipmentTree.getName());
        }
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(planInfo.getEmId());
        upkeepWorkOrder.setEmName(equipmentInfo.getEmName());
        upkeepWorkOrder.setWorkOrderCode(commonService.getBxWorkOrderCode());
        upkeepWorkOrder.setEmCode(equipmentInfo.getEmCode());
        upkeepWorkOrder.setEmSpecification(equipmentInfo.getEmSpecification());
        upkeepWorkOrder.setEmLocation(equipmentInfo.getEmLocation());
        upkeepWorkOrder.setUpkeepState(EnumRepState.PENDING_ANNOUNCE.getRepState());
        upkeepWorkOrder.setEmployeeId(0L);
        upkeepWorkOrder.setUpkeepStartTime(planInfo.getChangeTime());
        upkeepWorkOrder.setCreateTime(new Date());
        upkeepWorkOrderMapper.insertSelective(upkeepWorkOrder);
        List<UpkeepDbTask> upkeepDbTaskList = UpkeepDao.selectUpkeepDbTaskByTemplateId(planInfo.getTemplateId());
        List<Map<String, Object>> partList = UpkeepDao.selectUpkeepTaskPartByTemplateId(planInfo.getTemplateId());
        if(CollUtil.isNotEmpty(upkeepDbTaskList)){
            for(UpkeepDbTask upkeepDbTask:upkeepDbTaskList){
                UpkeepTask upkeepTask = new UpkeepTask();
                upkeepTask.setUpkeepId(upkeepWorkOrder.getUpkeepId());
                upkeepTask.setTaskId(upkeepDbTask.getId());
                upkeepTask.setTaskName(upkeepDbTask.getTaskName());
                upkeepTask.setTaskDesc(upkeepDbTask.getTaskDesc());
                upkeepTask.setIsComplete(1);
                upkeepTask.setCreateTime(new Date());
                upkeepTaskMapper.insertSelective(upkeepTask);
            }
        }

        if(CollUtil.isNotEmpty(partList)){
            List<UpkeepPart> upkeepPartList = new ArrayList<>();
            for(Map<String, Object> partMap:partList){
                Long partId = MapUtil.getLong(partMap,"partId");
                Integer partNum = MapUtil.getInt(partMap,"partNum");
                if (partId != null && partNum != null) {
                    UpkeepPart upkeepPart = new UpkeepPart();
                    upkeepPart.setUpkeepId(upkeepWorkOrder.getUpkeepId());
                    upkeepPart.setPartId(partId);
                    upkeepPart.setPartNum(partNum);
                    upkeepPart.setIsComplete(1);
                    upkeepPart.setCreateTime(new Date());
                    upkeepPartList.add(upkeepPart);
                }
            }
            if (CollUtil.isNotEmpty(upkeepPartList)) {
                UpkeepDao.insertUpkeepPartList(upkeepPartList);
            }
        }
        try {
            List<Long> userIdList = commonService.selectManagerUserIdList(3);
            for (Long userId:userIdList){
                //待办
                commonService.insertMessageBacklog(
                        userId,
                        "新增维保单待审核，请处理",
                        equipmentInfo.getEmName()+ "新增一个维保单，地点在【" + equipmentInfo.getEmLocation()  + "】，请审核维保申请信息。",
                        3, 1, upkeepWorkOrder.getUpkeepId(), upkeepWorkOrder.getWorkOrderCode()
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*private void insertFlow(Long repId, Long employeeId, int flowType, Long sourceId, Integer state, String flowDesc) {
        RepairWorkOrderFlow workOrderFlow = new RepairWorkOrderFlow();
        workOrderFlow.setRepId(repId);
        workOrderFlow.setEmployeeId(employeeId);
        workOrderFlow.setSourceId(sourceId);
        workOrderFlow.setFlowDesc(flowDesc);
        workOrderFlow.setFlowType(flowType);
        workOrderFlow.setState(state);
        workOrderFlow.setDisEmployeeId(0L);
        workOrderFlow.setCreateTime(new Date());
        repairWorkOrderFlowMapper.insert(workOrderFlow);
    }*/

    public void insertPatroFlow(
            long patrolId, int flowType, long sourceId,
            long employeeId, String flowDesc, Date date
    ) {
        PatrolWorkOrderFlow newPwof = new PatrolWorkOrderFlow();
        newPwof.setPatrolId(patrolId);
        newPwof.setPlanId(0L);
        newPwof.setFlowType(flowType);
        newPwof.setSourceId(sourceId);
        newPwof.setEmployeeId(employeeId);
        newPwof.setFlowDesc(flowDesc);
        newPwof.setIsSyn(0);
        newPwof.setCreateTime(date);
        patrolWorkOrderFlowMapper.insertSelective(newPwof);
    }

    public void insertTask(long patrolId, long treeId) {
        int index = 0;

        EquipmentTreeExample etExample = new EquipmentTreeExample();
        etExample.createCriteria().andBaseIdEqualTo(treeId);
        etExample.setOrderByClause("sort");
        List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
        for (EquipmentTree et : etList) {
            if (et.getEmType() == 0) {
                continue;
            }
            PatrolTemplateTaskExample ttExample = new PatrolTemplateTaskExample();
            ttExample.createCriteria().andTypeEqualTo(1).andEmTypeEqualTo(et.getEmType());
            ttExample.setOrderByClause("sort");
            List<PatrolTemplateTask> ttList = patrolTemplateTaskMapper.selectByExample(ttExample);
            if (ttList.size() == 0) {
                continue;
            }

            PatrolTree newPt = new PatrolTree();
            newPt.setPatrolId(patrolId);
            newPt.setType(1);
            newPt.setTypeId(et.getId());
            newPt.setState(2);
            newPt.setEmType(et.getEmType());
            newPt.setSort(index++);
            patrolTreeMapper.insert(newPt);

            for (PatrolTemplateTask tt : ttList) {
                PatrolTreeTask newPtt = new PatrolTreeTask();
                newPtt.setPatrolTreeId(newPt.getId());
                newPtt.setTaskId(tt.getId());
                newPtt.setState(1);
                newPtt.setIsRecorded(tt.getIsRecorded());
                newPtt.setSort(tt.getSort());
                patrolTreeTaskMapper.insert(newPtt);
            }
        }
        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        eiExample.createCriteria().andEmTreeEqualTo(treeId);
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        for (EquipmentInfo ei : eiList) {
            if (ei.getEmType() == 0) {
                continue;
            }
            PatrolTemplateTaskExample ttExample = new PatrolTemplateTaskExample();
            ttExample.createCriteria().andTypeEqualTo(1).andEmTypeEqualTo(ei.getEmType());
            ttExample.setOrderByClause("sort");
            List<PatrolTemplateTask> ttList = patrolTemplateTaskMapper.selectByExample(ttExample);
            if (ttList.size() == 0) {
                continue;
            }

            PatrolTree newPt = new PatrolTree();
            newPt.setPatrolId(patrolId);
            newPt.setType(2);
            newPt.setTypeId(ei.getId());
            newPt.setState((ei.getEmState() == 2 || ei.getEmState() == 3) ? 2 : 1);
            newPt.setEmType(ei.getEmType());
            newPt.setSort(index++);
            patrolTreeMapper.insert(newPt);

            for (PatrolTemplateTask tt : ttList) {
                PatrolTreeTask newPtt = new PatrolTreeTask();
                newPtt.setPatrolTreeId(newPt.getId());
                newPtt.setTaskId(tt.getId());
                newPtt.setState(1);
                newPtt.setIsRecorded(tt.getIsRecorded());
                newPtt.setSort(tt.getSort());
                patrolTreeTaskMapper.insert(newPtt);
            }
        }
        PatrolTemplateSubsystemExample subsystemExample = new PatrolTemplateSubsystemExample();
        subsystemExample.createCriteria().andSubsystemTreeIdEqualTo(treeId);
        List<PatrolTemplateSubsystem> patrolTemplateSubsystems = patrolTemplateSubsystemMapper.selectByExample(subsystemExample);
        for (PatrolTemplateSubsystem patrolTemplateSubsystem : patrolTemplateSubsystems) {
            PatrolTemplateTaskExample pttExample = new PatrolTemplateTaskExample();
            pttExample.createCriteria().andTypeEqualTo(2).andSubsystemIdEqualTo(patrolTemplateSubsystem.getId());
            pttExample.setOrderByClause("sort");
            List<PatrolTemplateTask> pttList = patrolTemplateTaskMapper.selectByExample(pttExample);

            PatrolTree newPt = new PatrolTree();
            newPt.setPatrolId(patrolId);
            newPt.setType(3);
            newPt.setTypeId(patrolTemplateSubsystem.getId());
            newPt.setState(2);
            newPt.setEmType(0);
            newPt.setSort(index++);
            patrolTreeMapper.insert(newPt);
            for (PatrolTemplateTask tt : pttList) {
                PatrolTreeTask newPtt = new PatrolTreeTask();
                newPtt.setPatrolTreeId(newPt.getId());
                newPtt.setTaskId(tt.getId());
                newPtt.setState(1);
                newPtt.setIsRecorded(tt.getIsRecorded());
                newPtt.setSort(tt.getSort());
                patrolTreeTaskMapper.insert(newPtt);
            }
        }
    }

}